import sqlite3
import json
import smtplib
from email.mime.text import MIMEText
import random
from soupsieve import select


class LoginManager():
    def __init__(self):
        try:
            self.conn = sqlite3.connect('class_manager.db')
        except:
            print("connect error")
    def ret_message(self,  message, role=0, status=False):
        if status == True:
            context = {
                "msg": message,
                "status": True,
                "role": role
            }
        else:
            context = {
                "msg": message,
                "status": False,
                "role":0
            }
        ret_json = json.dumps(context, ensure_ascii=False)
        return ret_json

    def pre_login(self, table_name, username, password):
        sql_statement = "select * from " + table_name +\
            " where (username = '"+username+"'"+" or phone ='" + \
            username+"') and password = '"+password+"'"
        cursor = self.conn.execute(sql_statement)
        values = cursor.fetchone()
        return values

    def login(self, username, password, role):
        # username or phone
        if(username == ""):
            info = self.ret_message("账号不能为空!")
            return info
        if(password == ""):
            info = self.ret_message("密码不能为空!")
            return info
        if role == 1:
            table_name = "user_admin"
            values = self.pre_login(table_name, username, password)
            if values==None or len(values) == 0:  # 进行错误处理
                info = self.ret_message("用户名或密码错误!")
                return info
            else:  # 结果正常
                info = self.ret_message("登录成功！", role, True)
                return info
        elif role == 2:
            table_name = "user_secretary"
            values = self.pre_login(table_name, username, password)
            if values==None or len(values) == 0:  # 进行错误处理
                info = self.ret_message("用户名或密码错误!")
                return info
            else:  # 结果正常
                info = self.ret_message("登录成功！", role, True)
                return info
        elif role == 3:
            table_name = "user_teacher"
            values = self.pre_login(table_name, username, password)
            if values==None or len(values) == 0:  # 进行错误处理
                info = self.ret_message("用户名或密码错误!")
                return info
            elif values[-1]==0:
                info = self.ret_message("用户尚未激活!")
                return info
            else:  # 结果正常
                info = self.ret_message("登录成功!", role, True)
                return info
        else:
            return self.ret_message("没有该用户!")

    def get_userinfo(self, table_name, username):
        sql_statement = "select * from " + table_name +\
            " where username = '"+username+"'"
        print(sql_statement)
        cursor = self.conn.execute(sql_statement)
        values = cursor.fetchall()
        return values

    def get_phoneinfo(self, table_name, phone):
        sql_statement = "select * from " + table_name +\
            " where phone = '"+phone+"'"
        print(sql_statement)
        cursor = self.conn.execute(sql_statement)
        values = cursor.fetchall()
        return values

    def register(self, username, truename, password, confirm_password, phone, email):
        if username and truename and password and confirm_password and phone and email:
            # 全部都有值才能进行下一步
            if password != confirm_password:
                return self.ret_message("两次密码不一致!")
            table_name = "user_teacher"
            values = self.get_userinfo(table_name, username)
            if len(values) != 0:
                return self.ret_message("用户名已存在!")
            values = self.get_phoneinfo(table_name, phone)
            if len(values) != 0:
                return self.ret_message("手机号已存在!")

            # 都不满足上述情况时，插入数据
            sql_statement = "Insert into "+table_name + \
                " (username,password,truename,role,phone,email,activate) values " + \
                "( '"+username+"','"+password+"','" + \
                truename+"',3,'"+phone+"','"+email+"',0)"
            try:
                cursor = self.conn.execute(sql_statement)
                self.conn.commit()
                return self.ret_message("注册成功!",3,True)
            except Exception as e:
                print(e)
                return self.ret_message("插入数据失败!")
        else:
            info = self.ret_message("不能有空数据!")
            return info

    def get_random_code(self):
        random_code = ""
        for i in range(6):
            ch = chr(random.randrange(ord('0'), ord('9') + 1))
            random_code += ch
        return random_code

    def sendCodeMessage(self, email):
        msg_from = 'noreply@nsnteam.top'
        passwd = 'bx8sY5bVuyLEf3wb'
        msg_to = email  # 收件人邮箱
        self.random_code = self.get_random_code()
        subject = "邮箱验证码"
        content = self.random_code
        msg = MIMEText(content)
        # 放入邮件主题
        msg['Subject'] = subject
        msg['From'] = msg_from
        msg['To'] = email
        try:
            s = smtplib.SMTP_SSL("smtp.exmail.qq.com", 465)
            s.login(msg_from, passwd)
            s.sendmail(msg_from, msg_to, msg.as_string())
            return self.ret_message("验证码发送成功!")
        except s.SMTPException as e:
            print(e)
        finally:
            s.quit()

    def forgotPassword(self, username, password, confirm_password, email, code):
        if username and password and confirm_password and email and code:
            if password != confirm_password:
                return self.ret_message("两次密码不一致!")
            if code != self.random_code:
                return self.ret_message("验证码错误!")
            # 修改密码
            sql_statement = "update user_teacher set password = '"+password+"' where username = '" +\
                username+"' or phone = '"+username+"'"
            print(sql_statement)
            try:
                self.conn.cursor().execute(sql_statement)
                self.conn.commit()
                return self.ret_message("重置密码成功,请返回登录!", 3, True)
            except Exception as e:
                print(e)
                return self.ret_message("重置密码失败!")
        else:
            info = self.ret_message("不能有空数据!")
            return info

class User():
    def __init__(self):
        try:
            self.conn = sqlite3.connect('class_manager.db')
        except:
            raise
    def select(self,username):
        sql = "select * from user_teacher where username=? or phone=?"
        cursor = self.conn.cursor()
        result = cursor.execute(sql,(username,username))
        if result:
            return result.fetchone()
        else:
            return None
    def select_name(self,truename,phone):
        sql = "select * from user_teacher where truename=? and phone=?"
        cursor = self.conn.cursor()
        result = cursor.execute(sql,(truename,phone))
        if result:
            return result.fetchone()
        else:
            return None
    def session(self,path,username):
        result = self.select(username)
        if result==None:
            return
        with open(path,"w") as f:
            content = "teacher," +result[0]+"," +result[2]
            f.write(content)
